package li.teng.android.xplanet;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;

/*
 * this is a wiki view of one position,user can view text and picture information of the position, user
 * can lauch a voice guide of the postion
 */
public class PositionWiki extends Activity implements OnSharedPreferenceChangeListener{

	boolean m_IsAutoSpeaking;
	private final Handler uiHandler = new Handler();
	
	private DialogManager dialogManager;
	private SharedPreferences sharedPreferences;
	WebView web2;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wiki);
		dialogManager = new DialogManager(this);
		web2 = (WebView) findViewById(R.id.welcome_web);
		web2.loadUrl("file:///android_asset/index.html");
		m_IsAutoSpeaking = false;
		Log.e(XplanetConstants.TAG,"Init TextToSpeechBeta");
		
	    sharedPreferences = getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0);
	    if (sharedPreferences != null) {
	      //reloadSharedPreferences(sharedPreferences, null);
	      sharedPreferences.registerOnSharedPreferenceChangeListener(this);
	    }		
	}

	@Override
	protected Dialog onCreateDialog(int id){
		return dialogManager.onCreateDialog(id);
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		super.onPrepareDialog(id, dialog);
		dialogManager.onPrepareDialog(id, dialog);
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.wiki, menu);
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		boolean m_IsSpeaking = VoiceGuide.getInstance(this).isSpeaking();
		menu.findItem(R.id.menu_start_voice)
		.setEnabled(!m_IsSpeaking)
		.setVisible(!m_IsSpeaking);
		menu.findItem(R.id.menu_stop_voice)
		.setEnabled(m_IsSpeaking)
		.setVisible(m_IsSpeaking);
		return true;
	}	  

	public boolean onOptionsItemSelected(MenuItem item) {  
		Log.d(XplanetConstants.TAG,"PosiotionWiki onOptionsItemSelected");
		switch (item.getItemId()) {
			case (R.id.menu_start_voice): 
				startVoiceWiki();
			return true;
			case (R.id.menu_stop_voice): 
				stopVoiceWiki();
			return true;
		}
		Log.d(XplanetConstants.TAG,"PosiotionWiki onOptionsItemSelected goon");
		return super.onOptionsItemSelected(item);
	}

	  @Override
	  public void onSharedPreferenceChanged(
	      final SharedPreferences sharedPreferences, final String key) {
	    Log.d(XplanetConstants.TAG,
	        "PositionWiki.onSharedPreferenceChanged: " + key);
	    if (key != null) {
	      uiHandler.post(new Runnable() {
	        @Override
	        public void run() {
	          reloadSharedPreferences(sharedPreferences, key);
	        }
	      });
	    }
	  }
	  
	  private void reloadSharedPreferences(SharedPreferences sharedPreferences,
		      String key) {
		  Log.d(XplanetConstants.TAG,"key = " + key + " R.string.selected_track_key = "+ R.string.selected_track_key);
		    if(key.equals(getString(R.string.selected_track_key))){
		    	Log.d(XplanetConstants.TAG,"PosiotionWiki reloadSharedPreferences");
		    	loadWiki(sharedPreferences.getLong(
		    	          getString(R.string.selected_track_key),-1));
		    }
		    
	  }
	  

    @Override
    protected void onDestroy() {   
    	super.onDestroy();
        // TODO Auto-generated method stub
//        if (mSpeech != null) {
//            mSpeech.stop();
//            mSpeech.shutdown();
//        }
    }

	private void startVoiceGuide(){
		Log.d(XplanetConstants.TAG,"startVoiceGuide");
		loadWiki(1);
	}

	private void stopVoiceGuide(){
		Log.d(XplanetConstants.TAG,"stopVoiceGuide");
		loadWiki(2);
	}

	private void startVoiceWiki(){
		Log.e(XplanetConstants.TAG,"startVoiceWiki");
		if(m_ArrayListTextToRead.size()>=1){
			String text = (String)m_ArrayListTextToRead.get(0);
			VoiceGuide.getInstance(this).speak(text);
		}
	}

	private void stopVoiceWiki(){
		Log.e(XplanetConstants.TAG,"stopVoiceWiki");
		VoiceGuide.getInstance(this).stop();
	}
	
	String m_TextToRead;
	ArrayList m_ArrayListTextToRead = new ArrayList();
	private void loadWiki(long id){
		Log.d(XplanetConstants.TAG,"loadWiki " + id);
        try{
            char data[]=new char[1024*32];
            m_ArrayListTextToRead.clear();
        	//m_FileReader = new FileReader("/sdcard/li.teng.android.xplanet/" + file); 
            String file_name = id + ".html";
            web2.loadUrl("file:///android_asset/" + file_name);
            InputStream fis = getAssets().open(file_name);
        	InputStreamReader reader = new InputStreamReader(fis);
        	//fis.re
        	int length = reader.read(data);
        	reader.close();
        	fis.close();
        	String text = new String(data,0,length);
        	Document doc = Jsoup.parse(text);
        	Elements links = doc.select("speak");
        	Log.d(XplanetConstants.TAG, "links.size() = " + links.size());
        	for(int i=0;i<links.size();i++){
        		m_ArrayListTextToRead.add(links.get(i).text());
    		}
        }catch(Exception ex){
        	Log.d(XplanetConstants.TAG,ex.toString());
        }
	}
}
